<?php

namespace app\jzshop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\jzshop\job\GoodsListAsync;
use app\jzshop\job\SupplierAsync;
use app\jzshop\model\Supcorp as ModelSupcorp;
use think\Db;
use think\Queue;

class Supcorp extends Admin
{
    /**
     * 品牌列表
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        // 查询
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder('coId asc');
        // 数据列表
        $data_list = ModelSupcorp::where($map)->order($order)->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTips('debug:' . Db::getLastSql(), 'warning')
            ->setSearch(['coName' => '公司名称', 'supplierId' => '供应商ID', 'supplierName' => '供应商名称']) // 设置搜索框
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['coId', '公司ID', 'text'],
                ['coName', '公司名称', 'text'],
                ['supplierId', '供应商ID', 'text'],
                ['supplierName', '供应商', 'text'],
                ['supplierLogo', '供应商Logo', 'img_url'],
                ['supplierTagNames', '供应商标签', 'text'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('async', [
                'title' => '同步数据',
                'icon'  => 'fa fa-fw fa-code-fork',
                'class' => 'btn btn-success',
                'href'  => url('add', ['supplierId' => '__supplierId__', 'type' => 0])
            ], ['area' => ['600px', '90%']])
            ->addRightButton('async', [
                'title' => '强制同步数据',
                'icon'  => 'fa fa-fw fa-code-fork',
                'class' => 'btn btn-success',
                'href'  => url('add', ['supplierId' => '__supplierId__', 'type' => 1])
            ], ['area' => ['600px', '90%']])
            ->addTopButton('async', [
                'title' => '同步供应商',
                'icon'  => 'fa fa-fw fa-code-fork',
                'class' => 'btn btn-success ajax-get',
                'href'  => url('async', ['is_sync_goods' => false])
            ])
            ->addOrder('id,coName')
            ->setRowList($data_list)
            ->fetch(); // 渲染模板
    }
    function async()
    {
        $is_sync_goods = $this->request->param('is_sync_goods', false);

        if (Queue::push(SupplierAsync::class, $is_sync_goods)) {
            // 记录行为
            $this->success('添加队列成功', 'index');
        } else {
            $this->error('添加队列失败');
        }
    }

    /**
     * 新增
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add()
    {
        // 表单数据
        $supplierId = $this->request->param('supplierId');
        $type = $this->request->param('type');
        if (Queue::push(GoodsListAsync::class, ['supplierId' => $supplierId, 'type' => $type])) {
            // 记录行为
            $this->success('添加队列成功', 'index');
        } else {
            $this->error('添加队列失败');
        }
    }

    /**
     * 编辑
     * @param null $id 链接id
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            // 验证
            $result = $this->validate($data, 'Brand');
            if (true !== $result) $this->error($result);

            if (ModelSupcorp::update($data)) {
                // 记录行为
                action_log('Brand_edit', 'jzshop_Brand', $id, UID, $data['coName']);
                $this->success('编辑成功', 'index');
            } else {
                $this->error('编辑失败');
            }
        }

        $info = ModelSupcorp::get($id);

        // 显示编辑页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden', 'id'],
                ['radio', 'type', '链接类型', '', [1 => '文字链接', 2 => '图片链接']],
                ['text', 'coName', '链接标题'],
                ['text', 'url', '链接地址', '请以 <code>http</code> 或 <code>https</code>开头'],
                ['image', 'logo', '链接LOGO'],
                ['tags', 'keywords', '关键词'],
                ['textarea', 'contact', '联系方式'],
                ['text', 'sort', '排序'],
                ['radio', 'status', '立即启用', '', ['否', '是']]
            ])
            ->setTrigger('type', 2, 'logo')
            ->setFormData($info)
            ->fetch();
    }

    /**
     * 删除品牌
     * @param array $record 行为日志
     * @author 蔡伟明 <314013107@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用品牌
     * @param array $record 行为日志
     * @author 蔡伟明 <314013107@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用品牌
     * @param array $record 行为日志
     * @author 蔡伟明 <314013107@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置品牌状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @author 蔡伟明 <314013107@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids        = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $Brand_coName = ModelSupcorp::where('id', 'in', $ids)->column('coName');
        return parent::setStatus($type, ['Brand_' . $type, 'jzshop_Brand', 0, UID, implode('、', $Brand_coName)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id      = input('post.pk', '');
        $field   = input('post.name', '');
        $value   = input('post.value', '');
        $Brand    = ModelSupcorp::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $Brand . ')，新值：(' . $value . ')';
        return parent::quickEdit(['Brand_edit', 'jzshop_Brand', $id, UID, $details]);
    }
}
